package com.zjitc.controller;

import com.zjitc.common.ServerResponse;
import com.zjitc.pojo.User;
import com.zjitc.service.UserService;
import com.zjitc.utils.MyNumber;
import com.zjitc.utils.Utils;
import com.zjitc.vo.ForgetPasswordDemo;
import com.zjitc.vo.Msg;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.NoSuchAlgorithmException;
import java.util.Random;
import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

/**
 * Create By IntelliJ IDEA
 *
 * @author: jsonor
 * @create-Time: 2017/11/7 9:17
 * @description: ${description}
 */
@Controller
@RequestMapping("/user")
public class UserController {

  private final String MSG = "msg";

  @Autowired
  private UserService service;

  private static final Logger log = Logger.getLogger(UserController.class);

  @RequestMapping(value = "/register",method = RequestMethod.POST)
  @ResponseBody
  public ServerResponse<User> register(User user, HttpSession session, HttpServletRequest request)
      throws UnsupportedEncodingException, NoSuchAlgorithmException {
    String code = user.getCode();
    String msgs = String.valueOf(session.getAttribute(MSG));

    if (msgs.equalsIgnoreCase(code)) {
      user.setUid(Utils.getUUID());
      user.setPassword(Utils.encoderByMd5(user.getPassword()));
      user.setState(0);
      user.setCode(Utils.getUUID());
      //获取项目绝对路径
      String path = request.getContextPath();
      boolean success = service.regiser(user, path);

      String msg, address;
      if (success) {
        msg = "注册成功，请前往邮箱进行激活";
        address = request.getContextPath() + "jsp/login";
        Msg m = new Msg(msg, address);
        return ServerResponse.createSuccess(m);
      }
    }
    return ServerResponse.createError("-1");
  }

  @RequestMapping("/active")
  public ModelAndView active(String uid, String code, HttpServletRequest request)
      throws ServletException, IOException {
    ModelAndView mv = new ModelAndView();
    boolean success = service.active(uid, code);
    String msg = success ? "激活成功" : "激活失败";
    String address = request.getContextPath() + "jsp/login";
    mv.addObject(MSG, msg);
    mv.addObject("address", address);
    mv.setViewName("jsp/msg");
    return mv;
  }

  @RequestMapping(value = "/login",method = RequestMethod.POST)
  @ResponseBody
  public ServerResponse<User> login(String username, String password, String code,
      HttpSession session) throws IOException, NoSuchAlgorithmException, ServletException {
    return service.login(username, password, code, session);
  }


  @RequestMapping("/loginOut")
  public ModelAndView loginOut(HttpSession session) throws ServletException, IOException {
    session.removeAttribute("user");
    ModelAndView mv = new ModelAndView();
    mv.setViewName("redirect:/index.do");
    return mv;
  }

  /**
   * 生成验证码
   */
  @RequestMapping("/code")
  public void code(HttpServletRequest request, HttpServletResponse response, HttpSession session)
      throws IOException {
    // 使用java图形界面技术绘制一张图片

    int charNum = 4;
    int width = 29 * 4;
    int height = 35;

    // 1. 创建一张内存图片
    BufferedImage bufferedImage = new BufferedImage(width, height,
        BufferedImage.TYPE_INT_RGB);

    // 2.获得绘图对象
    Graphics graphics = bufferedImage.getGraphics();

    // 3、绘制背景颜色
    graphics.setColor(Color.GRAY);
    graphics.fillRect(0, 0, width, height);

    // 4、绘制图片边框
    graphics.setColor(Color.WHITE);
    graphics.drawRect(0, 0, width - 1, height - 1);

    // 5、输出验证码内容
    graphics.setColor(Color.BLUE);
    graphics.setFont(new Font("宋体", Font.BOLD, 30));

    // 随机输出4个字符
    Graphics2D graphics2d = (Graphics2D) graphics;
    String s = "ABCDEFGHGKLMNPQRSTUVWXYZ23456789";
    Random random = new Random();
    //session中要用到
    String msg = "";
    int x = 5;
    int four = MyNumber.FOUR.ordinal();
    for (int i = 0; i < four; i++) {
      int index = random.nextInt(32);
      String content = String.valueOf(s.charAt(index));
      msg += content;
      double theta = random.nextInt(45) * Math.PI / 180;
      //让字体扭曲
      graphics2d.rotate(theta, x, 18);
      graphics2d.drawString(content, x, 18);
      graphics2d.rotate(-theta, x, 18);
      x += 29;
    }

    session.setAttribute(MSG, msg);

    // 释放资源
    graphics.dispose();

    // 图片输出 ImageIO
    ImageIO.write(bufferedImage, "jpg", response.getOutputStream());

  }


  @RequestMapping("/check")
  @ResponseBody
  public ServerResponse<User> check(String username) throws IOException {
    return service.checkUsername(username);
  }

  @RequestMapping("/checkPassword")
  @ResponseBody
  public ServerResponse checkpassword(String password, String uPassword) throws IOException {
    return service.checkpassword(password, uPassword);
  }


  @RequestMapping("/gotomsg")
  public ModelAndView registerTomsg(@RequestParam("msg") String msg,
      @RequestParam("address") String address) {
    ModelAndView modelAndView = new ModelAndView();
    modelAndView.addObject(MSG, msg);
    modelAndView.addObject("address", address);
    modelAndView.setViewName("jsp/msg");
    return modelAndView;
  }

  @RequestMapping("/gotologin")
  public String indextologin() {
    return "jsp/login";
  }

  @RequestMapping("/gotoregister")
  public String indextoregister() {
    return "jsp/register";
  }

  /**
   * ------------------------------------------------------------------
   */
  @RequestMapping("forgetPassword")
  public String forgetpassword() {
    return "jsp/forget_password";
  }

  @RequestMapping("forgetSendEmail")
  public void forgetSendEmail(ForgetPasswordDemo demo) {
    if (demo.getEmail() != null && demo.getUsername() != null) {
      service.forgetSendEmail(demo);
    }
  }

  @RequestMapping(value = "forgetCheckCode",method = RequestMethod.POST)
  @ResponseBody
  public ServerResponse forgetcheckcode(ForgetPasswordDemo demo, String code) {
    return service.forgetcheckcode(demo, code);
  }

  @RequestMapping("forgetGoReset")
  public ModelAndView forgetGoReset(String username) {
    String uid = service.finduidByusername(username);
    ModelAndView m = new ModelAndView("/jsp/forget_reset_password");
    m.addObject("uid", uid);
    return m;
  }

  @RequestMapping(value = "forgetResetPassword",method = RequestMethod.POST)
  @ResponseBody
  public ServerResponse forgetResetPassword(User user) {
    boolean s = service.forgetResetPassword(user);
    if (s == true) {
      return ServerResponse.createSuccess();
    }
    return ServerResponse.createError();
  }

  @RequestMapping("GotoResetPassword")
  public String gotoResetPassword() {
    return "/jsp/reset_password";
  }

  @RequestMapping(value = "resetPassword",method = RequestMethod.POST)
  @ResponseBody
  public ServerResponse resetPassword(
      @RequestParam(value = "username") String username,
      @RequestParam(value = "oldpassword") String oldPassword,
      @RequestParam(value = "newpassword") String newPassword,
      HttpSession session
  ) {
    return service.resetPassword(username, oldPassword, newPassword, session);
  }

//  ------------------------------------------------------------------------------------------

  @RequestMapping("searchmycollect")
  public ModelAndView searchMyCollect(HttpSession session,
      @RequestParam(value = "page",required = false,defaultValue = "0") String page){
    return service.searchMyCollect(session,page);
  }

}
